# _*_ coding utf-8 _*_
# FILENAME：SelectFactoryComponent.py
# DESCRIPTION: 工厂选择控件,基于QComboBox控件
# AUTH: 
# DATE: 2022/6/59:47 上午
from PyQt5.QtWidgets import *
from sqlalchemy import desc

from components.BaseComboBox import BaseComBoBox
from models.baseModel import get_session
from models.factoryModel import FactoryModel


class SelectFactoryComponent(QComboBox):

    __data = None

    def __init__(self, parent=None):
        super(SelectFactoryComponent, self).__init__()
        print("init")
        self.__data = self.init_data()
        arr = []
        for i in range(len(self.__data)):
            model = self.__data[i]
            val = model.name + '|' + str(model.id)
            arr.append(val)
        self.addItems(arr)

    def init_data(self):
        # print("init data")
        session = get_session()
        data = session.query(FactoryModel).filter(FactoryModel.is_del == 0).order_by(desc(FactoryModel.id)).all()
        session.close()
        return data

    def getId(self):
        data = self.currentText()
        arr = data.split('|')
        return arr[1]

    def getText(self):
        data = self.currentText()
        arr = data.split('|')
        return arr[0]

    def selectedById(self, id=0):
        for i in range(len(self.__data)):
            model = self.__data[i]
            if model.id == id:
                self.setCurrentIndex(i)
                break